package com.genghis.rapidcrm.util;

import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xulixin
 */
public final class RapidResourceUtil {

    private RapidResourceUtil() {
        // reserved.
    }

    private static Map<String, Boolean> resourceMap = new HashMap<>();

    public static final String RESOURCE_FILE_DIR = "static/";

    public static boolean resourceNotExists(String relativePath) {
        return !resourceExists(relativePath);
    }

    public static boolean resourceExists(String relativePath) {
        return checkResourceExists(relativePath, RESOURCE_FILE_DIR);
    }

    private static boolean checkResourceExists(String relativePath, String location) {
        String resUri = relativePath;
        if (!resUri.startsWith(location)) {
            resUri = location + resUri;
        }
        if (resourceMap.containsKey(resUri)) {
            return resourceMap.get(resUri);
        }
        boolean result = classpathResourceExists(resUri);
        resourceMap.put(resUri, result);
        return result;
    }

    private static boolean classpathResourceExists(String relativePath) {
        String resUri = relativePath;
        if (!resUri.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) {
            resUri = ResourceUtils.CLASSPATH_URL_PREFIX + resUri;
        }
        if (ResourceUtils.isUrl(resUri)) {
            try {
                File file = ResourceUtils.getFile(resUri);
                if (file != null) {
                    return true;
                }
            } catch (FileNotFoundException ignored) {
                // noops.
            }
        }
        return false;
    }
}
